package com.wltt.product.frfront.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author: wltt
 * @Date: 2020/7/1 15:26：
 * @Version: 1.0
 * @Description: TODO
 */
public abstract class Md5Util {

    /**
     * 最简单的md5运算
     *
     * @param str 原字符串
     * @return 字符编码
     */
    public static String getMD5String(String str) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update(str.getBytes());
        return new BigInteger(1, messageDigest.digest()).toString(16);
    }

    /**
     * 最简单的md5运算,同时撒盐
     *
     * @param str 原字符串
     * @param salt 盐
     * @return 字符编码
     */
    public static String getMD5String(String str, String salt) throws NoSuchAlgorithmException {
        return getMD5String(addSalt(str, salt));
    }

    /**
     * 撒盐
     *
     * @param str 原字符串
     * @param salt 盐
     */
    private static String addSalt(String str, String salt) {
        if (null == salt || salt.length() < 32) {
            throw new RuntimeException("salt长度不能小于32位");
        }

        char original[] = str.toCharArray();
        char salts[] = salt.toCharArray();

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            if (original.length > i) {
                sb.append(original[i]);
            }
            sb.append(salts[i]);
        }
        return sb.toString();
    }


    public static void main(String[] args) throws NoSuchAlgorithmException {
        System.out.println(getMD5String(""));
        System.out.println(getMD5String("wwww"));
        System.out.println(getMD5String("qqq", "11F77085A6BD33CD5D8809F8F6A86369"));
    }
}
